let queryAllTabsOpt = {
    currentWindow: true,
    pinned: false
}
let queryPinnedTabsOpt = {
    currentWindow: true,
    pinned: true
}

let recentSortedTabs = Array()

function reorderTabs(tabs) {
    for (let index = tabs.length - 1; index > -1; index--) {
        const tab = tabs[index];
        if (tab.index != index) {
            moved = true
            chrome.tabs.move(tab.id, { index: index })
        }
    }
}
let tabSortFunc = (a, b) => {
    if (a.url == b.url) {
        return 0
    } else if (a.url < b.url) {
        return -1
    } else return 1
}

function queryAndReorderTabs() {
    chrome.tabs.query(queryAllTabsOpt, function (tabs) {
        console.log(tabs.length)
        tabs.sort(tabSortFunc)
        // 分组
        reorderTabs(tabs)
    })
}
/**
 * 
 * @param {*} callback  
 */
function querySortedTabs(opt, _callback) {
    chrome.tabs.query(opt || queryAllTabsOpt, function (tabs) {
        tabs.sort(tabSortFunc)
        _callback(tabs)
    })
}


/**
 * 代码显示 popup
 */
function showPopupByShortCut() {
    chrome.action.setPopup({
        "popup": "/popups/popup.html"
    }, function () {
        console.log("popup is shown,triggered by shortcut!")
    })
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request == "requestConnection") {
        queryAndReorderTabs()
        querySortedTabs(null, function (sortedTabs) {
            chrome.runtime.sendMessage(sortedTabs, function (res) { })
        })
    } else if (request && request.id) {
        chrome.tabs.update(request.id, { active: true }, function (w) {

        })
    }
    console.log("rev" + request)
    sendResponse("done.." + request)
})


// 配置了 popup 则点击回调不会响应，需要在 popup.js 中向 background.js发消息知道被惦记了
// chrome.action.onClicked.addListener(function () {
//     console.log("onClicked>>>")
//     queryAndReorderTabs()
// })

/**
 * 
 *
 */
chrome.tabs.onCreated.addListener(function (tab) {
    console.log("onCreated??" + tab.url + "00" + tab.id + "---" + tab.title)
    if (tab.url) {
        console.log("heee")
        queryAndReorderTabs()
    }
})

var m
chrome.tabs.onMoved.addListener(function (tabId) {
    // console.dir("onMoved"+tabId)
    // chrome.tabs.get(tabId,function(tab){
    //     console.dir("onMoving:"+JSON.stringify(tab))
    // })
    if (m) {
        clearTimeout(m)
    }
    m = setTimeout(() => {
        queryAndReorderTabs()
        m = null;
    }, 350);
})

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    if (tab.status == "complete" && tab.url) {
        queryAndReorderTabs()
    }
})

chrome.commands.onCommand.addListener((command) => {
    console.log(JSON.stringify(command))
})


// background.js
chrome.runtime.onInstalled.addListener((reason) => {
    if (reason === chrome.runtime.OnInstalledReason.INSTALL) {
        checkCommandShortcuts();
    }
});

// Only use this function during the initial install phase. After
// installation the user may have intentionally unassigned commands.
function checkCommandShortcuts() {
    chrome.commands.getAll((commands) => {
        let missingShortcuts = [];
        console.log('iiiiiiiiii')

        for (let { name, shortcut } of commands) {
            if (shortcut === '') {
                missingShortcuts.push(name);
            }
        }

        if (missingShortcuts.length > 0) {
            console.log("llllllllllll")
            // Update the extension UI to inform the user that one or more
            // commands are currently unassigned.
        }
    });
}